<template>
  <div>
    <!--查询条件-->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item label="设备编码">
        <el-input
          v-model="queryParams.equipmentCode"
          placeholder="请输入设备编码"
          clearable
          style="width: 200px"
          @keyup.enter.native="getList()"
        />
        <!--@keyup.enter.native="handleQuery"-->
      </el-form-item>
      <el-form-item label="数据状态">
        <el-select
          v-model="queryParams.isException"
          placeholder="数据状态"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="收集时间">
        <el-date-picker
          v-model="rangeTime"
          style="width: 360px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList()">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQueryParams()">重置</el-button>
      </el-form-item>
    </el-form>

    <!--操作按钮-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="batchDeleteEquipmentData()"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-s-operation"
          size="mini"
          @click="showDataTypeRangeDialog()"
        >设置预警值</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          :loading="exportLoading"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="exportData2Excel()"
        >导出</el-button>
      </el-col>
    </el-row>

    <!--表格数据 开始-->
    <el-table
      v-loading="loading"
      :data="dataList"
      :header-cell-style="{background:'#F8F8F9'}"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="70" align="center" />
      <el-table-column
        type="index"
        label="序号"
      />
      <el-table-column label="收集设备编码" align="center" prop="equipmentCode" />
      <el-table-column :label="unit" align="center" prop="data" />
      <el-table-column label="数据状态" align="center">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.isException == 1" type="success">正常</el-tag>
          <el-tag v-else-if="scope.row.isException == 2" type="danger">异常</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最小正常值" align="center" prop="minData" />
      <el-table-column label="最大正常值" align="center" prop="maxData" />
      <el-table-column label="收集时间" align="center" prop="collectionTime" />
    </el-table>
    <!--表格数据 结束-->

    <!-- 分页组件 -->
    <el-pagination
      v-show="total > 0"
      background
      :total="total"
      :current-page.sync="queryParams.current"
      :page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 30, 50, 100, 200]"
      style="padding: 30px 0; text-align: center;"
      layout="total, sizes, prev, pager, next, jumper"
      @current-change="getList(queryParams.current)"
      @size-change="handleSizeChange"
    />

    <!--设备类型 开始-->

    <!--设备类型-->
    <el-dialog title="设备类型" :visible.sync="showDataTypeRangeVisible" width="50%" center>

      <!--设备类型操作按钮-->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="showEditDataTypeRange()"
          >修改</el-button>
        </el-col>
      </el-row>
      <!--设备类型表格-->
      <el-table
        ref="multipleTable"
        :data="dataTypeRangeList"
        :header-cell-style="{background:'#F8F8F9'}"
        @selection-change="handleSelectionChangeDataTypeRange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column
          type="index"
          label="序号"
          width="50"
        />
        <el-table-column property="name" label="数据类型名称" />
        <el-table-column property="minData" label="最小正常值" />
        <el-table-column property="maxData" label="最大正常值" />
      </el-table>
    </el-dialog>

    <!-- 设备类型弹出框 -->
    <el-dialog :title="dataTypeRangeDialogTitle" :visible.sync="operationDialogVisible" width="40%">
      <el-form ref="dataForm" :model="dataTypeRange" label-width="100px" size="small" style="padding-right: 40px;">
        <el-form-item label="设备类型" prop="name">
          <el-input v-model="dataTypeRange.name" disabled />
        </el-form-item>
        <el-form-item label="最小正常值">
          <el-input v-model="dataTypeRange.minData" />
        </el-form-item>
        <el-form-item label="最大正常值">
          <el-input v-model="dataTypeRange.maxData" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" icon="el-icon-refresh-right" @click="operationDialogVisible = false">取 消</el-button>
        <el-button type="primary" icon="el-icon-check" size="small" @click="saveOrUpdateDataTypeRange ()">确 定</el-button>
      </span>
    </el-dialog>

    <!--设备类型 结束-->

  </div>
</template>

<script>
import api from '@/api/hardware/data/data'
import dataTypeRangeApi from '@/api/hardware/data/dataTypeRange'
import fileApi from '@/api/file'
import download from '@/utils/download'

export default {
  name: 'Data',
  props: ['dataType', 'unit', 'name'],
  data() {
    return {
      loading: true,
      dataList: [],
      equipmentData: {},
      total: 0, // 总记录数
      queryParams: {
        current: 1, // 页码
        pageSize: 20, // 每页记录数
        isException: null, // 数据状态
        equipmentCode: null,
        beginTime: '',
        endTime: ''
      },
      rangeTime: [],
      multipleSelection: [],

      showSearch: true,
      options: [
        {
          value: 1,
          label: '正常'
        }, {
          value: 2,
          label: '异常'
        },
        {
          value: 0,
          label: '未知'
        }
      ],
      exportLoading: false,

      // 预警列表
      dataTypeRangeList: [],
      // 预警
      dataTypeRange: {},
      // 显示预警
      showDataTypeRangeVisible: false,
      // 显示预警添加修改操作弹出框
      operationDialogVisible: false,
      // 预警标题
      dataTypeRangeDialogTitle: '',
      multipleSelectionDataTypeRange: []
    }
  },
  beforeMount() {
    this.getList()
    this.getDataTypeRangeList()
  },
  methods: {

    /**
     * 导出数据到Excel
     */
    async exportData2Excel() {
      try {
        this.exportLoading = true
        if (this.rangeTime === null) {
          this.queryParams.beginTime = null
          this.queryParams.endTime = null
        } else {
          this.queryParams.beginTime = this.rangeTime[0]
          this.queryParams.endTime = this.rangeTime[1]
        }
        const res = await fileApi.exportEquipmentDataExcel({
          ...this.queryParams,
          dataType: Number.parseInt(this.dataType)
        })

        download.excel(res, name)
      } finally {
        this.exportLoading = false
      }
    },

    /**
     * 显示预警管理
     */
    showDataTypeRangeDialog() {
      this.showDataTypeRangeVisible = true
      this.$refs.multipleTable.clearSelection()
    },

    // 每当多选选项发生变化的时候调用
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    /**
     * 批量删除
     */
    batchDeleteEquipmentData() {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const idList = []
        this.multipleSelection.forEach(equipmentData => { idList.push(equipmentData.id) })
        const res = await api.batchDeleteEquipmentData(idList)
        await this.getList()
        this.$message.success(res.message || '恭喜，批量删除操作成功！')
      }).catch()
    },

    /**
     * 每页大小发生变化的回调
     *
     * @param pageSize
     */
    handleSizeChange(size) {
      this.queryParams.pageSize = size
      this.getList()
    },

    /**
     * 重置查询表单
     */
    resetQueryParams() {
      this.queryParams.code = null
      this.rangeTime = []
      this.queryParams.isException = null
      this.getList()
    },

    /**
     * 分页查询数据
     *
     * @param pageNum 查询第几页，无参默认1
     * @returns {Promise<void>}
     */
    async getList(pageNum = 1) {
      try {
        this.queryParams.current = pageNum
        if (this.rangeTime === null) {
          this.queryParams.beginTime = null
          this.queryParams.endTime = null
        } else {
          this.queryParams.beginTime = this.rangeTime[0]
          this.queryParams.endTime = this.rangeTime[1]
        }
        const res = await api.listEquipmentDataByPage({ ...this.queryParams, dataType: Number.parseInt(this.dataType) })
        this.dataList = res.data.records
        this.total = res.data.total
        this.queryParams.current = res.data.current
        this.queryParams.pageSize = res.data.size
      } finally {
        this.loading = false
      }
    },

    // 预警

    /**
     * 弹出设备类型添加的表单
     */
    showAddDataTypeRange() {
      this.dataTypeRangeDialogTitle = '新建设备类型'
      this.operationDialogVisible = true
      this.dataTypeRange = {}
    },

    /**
     * 弹出设备类型编辑的表单
     *
     * @param id
     */
    async showEditDataTypeRange() {
      console.log(this.multipleSelectionDataTypeRange.length)
      if (this.multipleSelectionDataTypeRange.length === 0) {
        this.$message.warning('请选择要修改的数据！')
        return
      }
      if (this.multipleSelectionDataTypeRange.length > 1) {
        this.$message.warning('请选择一条修改的数据！')
        return
      }
      this.dataTypeRangeDialogTitle = '编辑设备类型'
      this.operationDialogVisible = true
      this.dataTypeRange = {}
      const id = this.multipleSelectionDataTypeRange[0].id
      const res = await dataTypeRangeApi.getDataTypeRangeById(id)
      this.dataTypeRange = res.data
    },

    /**
     * 设备类型发送添加或更新请求
     */
    saveOrUpdateDataTypeRange() {
      if (!this.dataTypeRange.id) {
        this.addDataTypeRange()
      } else {
        this.updateDataTypeRange()
      }
    },

    /**
     * 创建设备类型
     */
    async addDataTypeRange() {
      const res = await dataTypeRangeApi.addDataTypeRange(this.dataTypeRange)
      this.$message.success(res.message || '恭喜，添加操作成功！')
      this.operationDialogVisible = false
      await this.getDataTypeRangeList()
    },

    /**
     * 批量删除
     */
    batchDeleteDataTypeRange() {
      if (this.multipleSelectionDataTypeRange.length === 0) {
        this.$message.warning('请选择要删除的记录！')
        return
      }
      this.$confirm('此操作将永久删除记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const idList = []
        this.multipleSelectionDataTypeRange.forEach(dataTypeRange => { idList.push(dataTypeRange.id) })
        const res = await dataTypeRangeApi.batchDeleteDataTypeRange(idList)
        // TODO 是否要跳到当前页
        await this.dataTypeRangeList()
        this.$message.success(res.message || '恭喜，批量删除操作成功！')
      }).catch()
    },

    /**
     * 更新设备
     */
    async updateDataTypeRange() {
      const res = await dataTypeRangeApi.updateDataTypeRange(this.dataTypeRange)
      this.$message.success(res.message || '恭喜，修改操作成功！')
      this.operationDialogVisible = false
      await this.getDataTypeRangeList()
    },

    // 设备类型多选回调处理
    handleSelectionChangeDataTypeRange(selection) {
      this.multipleSelectionDataTypeRange = selection
    },

    /**
     * 获取所有设备类型信息
     *
     * @returns {Promise<void>}
     */
    async getDataTypeRangeList() {
      const res = await dataTypeRangeApi.listDataTypeRange()
      this.dataTypeRangeList = res.data
    }
  }
}
</script>

<style scoped>

</style>
